#include "comm.hpp"

int main()
{
    Log("child pid is :", Debug) << getpid() << endl;
    key_t k = ftok(PATH_NAME, PROJ_ID);
    if (k < 0)
    {
        Log("create key failed", Error) << "client key : " << k << endl;
        exit(1);
    }
    Log("create key done", Debug) << "client key : " << k << endl;

    // 获取共享内存
    int shmid = shmget(k, SHM_SIZE, 0);
    if (shmid < 0)
    {
        Log("create shm failed", Error) << "client key : " << k << endl;
        exit(2);
    }
    Log("create shm success", Debug) << "client key : " << k << endl;

    // sleep(10);
    //  把自己当前进程关联共享内存
    char *shmaddr = (char *)shmat(shmid, nullptr, 0);
    if (shmaddr == nullptr)
    {
        Log("attach shm failed", Error) << "client key : " << k << endl;
        exit(3);
    }
    Log("attach shm done", Debug) << "client key : " << k << endl;
    // sleep(10);

    // 使用共享内存

    int fd=OpenFIFO(FIFO_NAME,WRITE);

    while (true)
    {
        ssize_t s = read(0, shmaddr, SHM_SIZE - 1); // 从0（键盘）读取数据，然后直接按地址存入到共享内存中
        if (s > 0)                                  // 读取成功
        {
            //假如输入quit最后又按一下回车，其实是输入了5个字符，
            //此时s是5，那s-1=4就是数组最后的下标，该下标指向的最后一个元素值为\n，
            //那把最后一个元素设置为\0，就成了最后只保留quit
            shmaddr[s - 1] = 0; // 最后一个位置加\0
            Signal(fd);//写入数据
            if (strcmp(shmaddr, "quit") == 0)
                break;
        }
    }

    CloseFifo(fd);
    /* char a = 'a';
     for (; a <= 'c'; a++)
     {
         // 每次向共享内存起始地址写入
         snprintf(shmaddr, SHM_SIZE - 1,
                  "hello,我是其他进程，我的pid:%d,inc:%c\n",
                  getpid(), a);
         sleep(5);
     }
     strcpy(shmaddr, "quit");*/

    // 去除关联
    int n = shmdt(shmaddr);
    assert(n != -1);
    Log("detach shm done", Debug) << "client key : " << k << endl;
    // sleep(10);
    //  client不需要删除共享内存

    return 0;
}